package mysql

import (
	"io"
	"text/template"

	"gitee.com/lipore/plume/db_gorm/gen/code"
	"gitee.com/lipore/plume/db_gorm/gen/spec"
)

type deleteMethodData struct {
	repositoryMethodData
	intOrBoolReturnData
	Entity code.Type
	Query  string
}

var deleteMethodTemplate = `
{{block "repositoryMethod" .}}{{end}}{
	entity := &{{typeToCode .Entity}}{}
    conn, err := db_gorm.LoadTx(ctx)
	if err != nil{
	{{- block "errorReturnStmt" .}}{{end -}}
	}
	var result *gorm.DB
	err = conn.Transaction(func(tx *gorm.DB) error {
		result = conn{{.Query}}.Delete(&entity)
		return result.Error
	})
	if err != nil {
	{{- block "errorReturnStmt" .}}{{end -}}
	}
	{{- block "returnStmt" .}}{{end}}
}`

func renderDeleteMethod(s spec.MethodSpec, entity code.Type, repository code.Type, operation spec.DeleteOperation, writer io.Writer) error {
	tmpl := template.New("delete Method")
	tmpl, err := renderRepositoryMethod(tmpl)
	if err != nil {
		return err
	}

	tmpl, err = renderReturnStmt(tmpl)

	tmpl, err = tmpl.Parse(deleteMethodTemplate)
	if err != nil {
		return err
	}

	query, err := renderQueryStmt(s, operation.Query)
	if err != nil {
		return err
	}
	tmplData := deleteMethodData{
		repositoryMethodData: repositoryMethodData{Receiver: code.Param{Name: "repository", Type: code.PointerType{ContainedType: repository}}, Spec: s},
		intOrBoolReturnData: intOrBoolReturnData{
			IntReturn: operation.Mode == spec.QueryModeMany,
		},
		Entity: entity,
		Query:  query,
	}

	return tmpl.Execute(writer, tmplData)
}
